package sk.octopuss.archery.utils;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.MessageInterpolator;
import javax.validation.Validation;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;
@Component(value="CustomMessageInterpolator")
public class CustomMessageInterpolator implements MessageInterpolator, MessageSourceAware{
	
	MessageSource messageSource;
	
	//private static final Pattern MESSAGE_PARAMETER_PATTERN = Pattern.compile("(\\{[^\\}]+?\\})");
	private static final Pattern MESSAGE_PARAMETER_PATTERN= Pattern.compile("\\${1}(([a-zA-z]+[.]*)*)");

	private final MessageInterpolator interpolator;

    public CustomMessageInterpolator() {
        //we need to delegate to the default interpolator
        this.interpolator = Validation.byDefaultProvider().configure().getDefaultMessageInterpolator();
    }
	
	
	@Override
	public String interpolate(final String message, final Context context) {
		String resolvedMessage = interpolator.interpolate(message, context);
		resolvedMessage = replaceWithPattern(resolvedMessage, context.getValidatedValue());
		return resolvedMessage;
	}
	
	@Override
	public String interpolate(final String message, final Context context, final Locale locale) {
		String resolvedMessage = interpolator.interpolate(message, context, locale);
		resolvedMessage = replaceWithPattern(resolvedMessage, context.getValidatedValue());
		return resolvedMessage;
	}

	private String replaceWithPattern(final String resolvedMessage, final Object validatedValue) {
		final Matcher matcher = MESSAGE_PARAMETER_PATTERN.matcher(resolvedMessage);
		String parameter = null;
		String regex = null;
		boolean found = false;
		while (matcher.find()) {
			parameter = matcher.group(1);
				try {
					regex = messageSource.getMessage(parameter,null,Locale.ROOT);
					regex = regex.replace("$", "\\$").replace("^", "\\^");
					found = true;
				} catch (final Exception e) {
					e.printStackTrace();
				}
		}
		if (found) {
		return matcher.replaceAll(regex);
		}else {
			return resolvedMessage;
		}
				
		
	}


	@Override
	public void setMessageSource(final MessageSource messageSource) {
		this.messageSource =messageSource; 
		
	}

}